﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class InvBackUpDA : IInvBackUpDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string EXECUTE_DATE = "@EXECUTE_DATE";
        private string LOC = "@LOC";
        private string LOT = "@LOT";
        private string LPN_ID = "@LPN_ID";
        private string OWNER_ID = "@OWNER_ID";
        private string QTY = "@QTY";
        private string SKU_ID = "@SKU_ID";
        private string SQL_BACK_UP = "INSERT INTO @_@INV_BACK_UP SELECT  WH_ID, '@EXECUTE_DATE',LOT,LOC,LPN_ID,OWNER_ID,SKU_ID,QTY,STATUS,'DBA',GETDATE(),'DBA',GETDATE() FROM @_@INV_LOT_LOC_LPN WHERE QTY>0 ";
        private string SQL_CHECK_INV_BACK_UP_ID_UNIQUE = " SELECT COUNT(1) FROM @_@INV_BACK_UP WHERE ROWID = @ROWID AND EXECUTE_DATE = @EXECUTE_DATE ";
        private string SQL_DELETE_INV_BACK_UP = " DELETE FROM @_@INV_BACK_UP WHERE ROWID = @ROWID AND EXECUTE_DATE = @EXECUTE_DATE ";
        private string SQL_INSERT_INV_BACK_UP = " INSERT INTO @_@INV_BACK_UP ( WH_ID, EXECUTE_DATE, LOT, LOC, LPN_ID, OWNER_ID, SKU_ID, QTY, STATUS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @WH_ID, @EXECUTE_DATE, @LOT, @LOC, @LPN_ID, @OWNER_ID, @SKU_ID, @QTY, @STATUS, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_INV_BACK_UP = " SELECT  ROWID, WH_ID, EXECUTE_DATE, LOT, LOC, LPN_ID, OWNER_ID, SKU_ID, QTY, STATUS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@INV_BACK_UP ";
        private string SQL_SELECT_BACK_UP = "SELECT OWNER_ID,SKU_ID,LOT,SUM(QTY) AS QTY FROM @_@INV_BACK_UP ";
        private string SQL_UPDATE_INV_BACK_UP = " UPDATE @_@INV_BACK_UP SET WH_ID = @WH_ID, LOT = @LOT, LOC = @LOC, LPN_ID = @LPN_ID, OWNER_ID = @OWNER_ID, SKU_ID = @SKU_ID, QTY = @QTY, STATUS = @STATUS, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE ROWID = @ROWID AND EXECUTE_DATE = @EXECUTE_DATE  ";
        private string STATUS = "@STATUS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckInvBackUpIDUnique(string invBackUpID, string execute_date, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", invBackUpID), new SqlParameter("@EXECUTE_DATE", execute_date) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_INV_BACK_UP_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckInvBackUpIDUnique(DataBase dataBase, DbTransaction tran, string invBackUpID, string execute_date, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", invBackUpID), new SqlParameter("@EXECUTE_DATE", execute_date) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_INV_BACK_UP_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteInvBackUp(List<string> invBackUpID, string execute_date, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int j = 0; j < invBackUpID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", invBackUpID[j]), new SqlParameter("@EXECUTE_DATE", execute_date) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteInvBackUp(DataBase dataBase, DbTransaction tran, string execute_date, string whLoginID)
        {
            int result = 0;
            string sql = "DELETE FROM @_@INV_BACK_UP WHERE convert(varchar(20),EXECUTE_DATE,23)  = @EXECUTE_DATE ";
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EXECUTE_DATE", execute_date) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, sql.Replace("@_@", whLoginID), paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteInvBackUp(DataBase dataBase, DbTransaction tran, List<string> invBackUpID, string execute_date, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < invBackUpID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ROWID", invBackUpID[j]), new SqlParameter("@EXECUTE_DATE", execute_date) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllInvBackUp(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllInvBackUp(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public List<InvBackUpInfo> GetInvBackUpByExecuteDate(string execute_date, string whLoginID)
        {
            string sql = this.SQL_SELECT_BACK_UP.Replace("@_@", whLoginID) + " WHERE  EXECUTE_DATE = @EXECUTE_DATE GROUP BY  OWNER_ID,SKU_ID,LOT ORDER BY OWNER_ID ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EXECUTE_DATE", execute_date) };
            List<InvBackUpInfo> invBackUpInfoList = new List<InvBackUpInfo>();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                while (reader.Read())
                {
                    InvBackUpInfo invBackUpInfo = new InvBackUpInfo(reader["OWNER_ID"].ToString(), reader["SKU_ID"].ToString(), (reader["QTY"].ToString() != "") ? decimal.Parse(reader["QTY"].ToString()) : 0M, reader["LOT"].ToString());
                    invBackUpInfoList.Add(invBackUpInfo);
                }
            }
            return invBackUpInfoList;
        }

        public InvBackUpInfo GetInvBackUpByID(string execute_date, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID) + " WHERE convert(varchar(20),EXECUTE_DATE,23)  = @EXECUTE_DATE  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EXECUTE_DATE", execute_date) };
            InvBackUpInfo invBackUpInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    DateTime CS00003;
                    invBackUpInfo = new InvBackUpInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), (reader["EXECUTE_DATE"].ToString() != "") ? DateTime.Parse(reader["EXECUTE_DATE"].ToString()) : (CS00003 = new DateTime()), reader["LOT"].ToString(), reader["LOC"].ToString(), reader["LPN_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["SKU_ID"].ToString(), (reader["QTY"].ToString() != "") ? decimal.Parse(reader["QTY"].ToString()) : 0M, reader["STATUS"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00003 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return invBackUpInfo;
        }

        public InvBackUpInfo GetInvBackUpByID(DataBase dataBase, DbTransaction tran, string execute_date, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID) + " WHERE convert(varchar(20),EXECUTE_DATE,23) = @EXECUTE_DATE  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@EXECUTE_DATE", execute_date) };
            InvBackUpInfo invBackUpInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                DateTime CS00003;
                invBackUpInfo = new InvBackUpInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), (reader["EXECUTE_DATE"].ToString() != "") ? DateTime.Parse(reader["EXECUTE_DATE"].ToString()) : (CS00003 = new DateTime()), reader["LOT"].ToString(), reader["LOC"].ToString(), reader["LPN_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["SKU_ID"].ToString(), (reader["QTY"].ToString() != "") ? decimal.Parse(reader["QTY"].ToString()) : 0M, reader["STATUS"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00003 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return invBackUpInfo;
        }

        public DataSet GetInvBackUpByQueryList(List<string> sqlWhere, InvBackUpQueryEntity invbackupQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!invbackupQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, invbackupQuery.CurrentPage, invbackupQuery.PageSize, invbackupQuery.SortField, invbackupQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetInvBackUpByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, InvBackUpQueryEntity invbackupQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_INV_BACK_UP.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, invbackupQuery.CurrentPage, invbackupQuery.PageSize, invbackupQuery.SortField, invbackupQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertInvBackUp(InvBackUpInfo invBackUpInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                invBackUpInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_InvBackUp_Parameters(invBackUpInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertInvBackUp(DataBase dataBase, DbTransaction tran, InvBackUpInfo invBackUpInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                invBackUpInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_InvBackUp_Parameters(invBackUpInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int InvBackUpDateByInvLocLotLpn(DataBase dataBase, DbTransaction tran, string executeDate, string whLoginID)
        {
            int result = 0;
            try
            {
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_BACK_UP.Replace("@EXECUTE_DATE", executeDate).Replace("@_@", whLoginID));
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_InvBackUp_Parameters(InvBackUpInfo invBackUpInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.EXECUTE_DATE, SqlDbType.DateTime, 8), new SqlParameter(this.LOT, SqlDbType.VarChar, 20), new SqlParameter(this.LOC, SqlDbType.VarChar, 20), new SqlParameter(this.LPN_ID, SqlDbType.VarChar, 20), new SqlParameter(this.OWNER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.SKU_ID, SqlDbType.VarChar, 50), new SqlParameter(this.QTY, SqlDbType.Decimal, 13), new SqlParameter(this.STATUS, SqlDbType.VarChar, 20), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            if (!string.IsNullOrEmpty(invBackUpInfo.WhID))
            {
                paramArray[0].Value = invBackUpInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = invBackUpInfo.ExecuteDate;
            if (!string.IsNullOrEmpty(invBackUpInfo.Lot))
            {
                paramArray[2].Value = invBackUpInfo.Lot;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(invBackUpInfo.Loc))
            {
                paramArray[3].Value = invBackUpInfo.Loc;
            }
            else
            {
                paramArray[3].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(invBackUpInfo.LpnID))
            {
                paramArray[4].Value = invBackUpInfo.LpnID;
            }
            else
            {
                paramArray[4].Value = DBNull.Value;
            }
            paramArray[5].Value = invBackUpInfo.OwnerID;
            paramArray[6].Value = invBackUpInfo.SkuID;
            paramArray[7].Value = invBackUpInfo.Qty;
            paramArray[8].Value = invBackUpInfo.Status;
            paramArray[9].Value = invBackUpInfo.CreatedBy;
            paramArray[10].Value = invBackUpInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateInvBackUp(InvBackUpInfo invBackUpInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                invBackUpInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_InvBackUp_Parameters(invBackUpInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateInvBackUp(DataBase dataBase, DbTransaction tran, InvBackUpInfo invBackUpInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                invBackUpInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_InvBackUp_Parameters(invBackUpInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_INV_BACK_UP.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

